<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>活动分类管理</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css" rel="stylesheet">
  <style>
    :root {
      --primary-color: #6f42c1;
      --secondary-color: #007bff;
      --success-color: #20c997;
      --warning-color: #ffc107;
      --danger-color: #dc3545;
      --light-bg: #f8f9fa;
    }

    body {
      font-family: 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
      background-color: #f0f2f5;
      color: #333;
      padding: 20px;
    }

    .header {
      background: linear-gradient(135deg, var(--primary-color), #5a32a3);
      color: white;
      padding: 25px;
      border-radius: 15px;
      margin-bottom: 25px;
      box-shadow: 0 6px 15px rgba(111, 66, 193, 0.2);
    }

    .card {
      border-radius: 15px;
      box-shadow: 0 4px 20px rgba(0,0,0,0.08);
      border: none;
      margin-bottom: 25px;
      transition: transform 0.3s ease;
    }

    .card:hover {
      transform: translateY(-5px);
    }

    .card-header {
      background: transparent;
      border-bottom: 1px solid rgba(0,0,0,0.05);
      font-weight: 600;
      padding: 1.25rem 1.5rem;
    }

    .btn-primary {
      background-color: var(--primary-color);
      border-color: var(--primary-color);
    }

    .btn-primary:hover {
      background-color: #5a32a3;
      border-color: #5a32a3;
    }

    .action-btn {
      margin: 0 3px;
    }

    .table th {
      font-weight: 600;
    }

    .table-hover tbody tr:hover {
      background-color: rgba(111, 66, 193, 0.05);
    }

    .modal-content {
      border-radius: 15px;
      border: none;
    }

    .form-control, .form-select {
      border-radius: 10px;
      padding: 10px 15px;
    }

    .toast-container {
      z-index: 1050;
    }

    .stats-card {
      text-align: center;
      padding: 20px;
    }

    .stats-card .number {
      font-size: 2rem;
      font-weight: 700;
      color: var(--primary-color);
    }

    .stats-card .label {
      color: #6c757d;
      font-weight: 500;
    }
  </style>
</head>
<body>
<!-- 头部 -->
<div class="header">
  <div class="container">
    <div class="d-flex justify-content-between align-items-center">
      <div>
        <h1><i class="bi bi-tags me-2"></i>活动分类管理</h1>
        <p class="mb-0">管理系统中的活动分类信息</p>
      </div>
      <div>
        <button class="btn btn-light" onclick="location.href='index.html'">
          <i class="bi bi-arrow-left-circle me-1"></i>返回首页
        </button>
      </div>
    </div>
  </div>
</div>

<div class="container">
  <!-- 统计卡片 -->
  <div class="row mb-4">
    <div class="col-md-12">
      <div class="card">
        <div class="card-body">
          <div class="d-flex justify-content-between align-items-center">
            <div class="stats-card">
              <div class="number" id="totalTypes">0</div>
              <div class="label">总分类数</div>
            </div>
            <div>
              <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#typeModal">
                <i class="bi bi-plus-circle me-1"></i>新增分类
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- 分类列表 -->
  <div class="card">
    <div class="card-header d-flex justify-content-between align-items-center">
      <span><i class="bi bi-list me-1"></i>活动分类列表</span>
      <button class="btn btn-sm btn-outline-primary" onclick="loadActivityTypes()">
        <i class="bi bi-arrow-clockwise me-1"></i>刷新
      </button>
    </div>
    <div class="card-body">
      <div class="table-responsive">
        <table class="table table-hover">
          <thead>
          <tr>
            <th>分类ID</th>
            <th>分类名称</th>
            <th>分类描述</th>
            <th>操作</th>
          </tr>
          </thead>
          <tbody id="activityTypeTableBody">
          <!-- 数据将通过JavaScript动态加载 -->
          </tbody>
        </table>
      </div>

      <!-- 空状态 -->
      <div id="emptyState" class="text-center py-5" style="display: none;">
        <i class="bi bi-folder me-2" style="font-size: 3rem; color: #dee2e6;"></i>
        <h4 class="mt-3">暂无活动分类</h4>
        <p class="text-muted">点击"新增分类"按钮创建第一个活动分类</p>
      </div>
    </div>
  </div>
</div>

<!-- 新增/编辑分类模态框 -->
<div class="modal fade" id="typeModal" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="typeModalLabel">
          <i class="bi bi-tag me-1"></i><span id="modalTitle">新增活动分类</span>
        </h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <form id="typeForm">
          <input type="hidden" id="type_id">
          <div class="mb-3">
            <label for="type_name" class="form-label">分类名称 <span class="text-danger">*</span></label>
            <input type="text" class="form-control" id="type_name" required>
          </div>
          <div class="mb-3">
            <label for="description" class="form-label">分类描述</label>
            <textarea class="form-control" id="description" rows="3"></textarea>
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
        <button type="button" class="btn btn-primary" id="saveTypeBtn">保存</button>
      </div>
    </div>
  </div>
</div>

<!-- Toast提示 -->
<div class="toast-container position-fixed bottom-0 end-0 p-3">
  <div id="toast" class="toast" role="alert">
    <div class="toast-header">
      <strong class="me-auto">提示</strong>
      <button type="button" class="btn-close" data-bs-dismiss="toast"></button>
    </div>
    <div class="toast-body" id="toastMessage"></div>
  </div>
</div>

<!-- JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
  // API基础URL
  const API_BASE = '/activity-types';

  // 初始化页面
  document.addEventListener('DOMContentLoaded', function() {
    loadActivityTypes();

    // 绑定事件
    document.getElementById('saveTypeBtn').addEventListener('click', saveActivityType);
  });

  // 加载活动分类数据
  function loadActivityTypes() {
    fetch(API_BASE)
            .then(response => response.json())
            .then(data => {
              renderActivityTypes(data);
              updateStats(data.length);
            })
            .catch(error => {
              console.error('加载数据出错:', error);
              showToast('加载数据出错', 'error');
            });
  }

  // 渲染活动分类表格
  function renderActivityTypes(types) {
    const tbody = document.getElementById('activityTypeTableBody');
    const emptyState = document.getElementById('emptyState');

    tbody.innerHTML = '';

    if (!types || types.length === 0) {
      emptyState.style.display = 'block';
      return;
    }

    emptyState.style.display = 'none';

    types.forEach(type => {
      const row = document.createElement('tr');
      row.innerHTML = `
                    <td>${type.type_id || '-'}</td>
                    <td>${type.type_name || '-'}</td>
                    <td>${type.description || '-'}</td>
                    <td>
                        <button class="btn btn-sm btn-outline-primary action-btn" onclick="editActivityType(${type.type_id})">
                            <i class="bi bi-pencil"></i>
                        </button>
                        <button class="btn btn-sm btn-outline-danger action-btn" onclick="deleteActivityType(${type.type_id})">
                            <i class="bi bi-trash"></i>
                        </button>
                    </td>
                `;
      tbody.appendChild(row);
    });
  }

  // 更新统计数据
  function updateStats(count) {
    document.getElementById('totalTypes').textContent = count;
  }

  // 编辑活动分类
  function editActivityType(typeId) {
    fetch(`${API_BASE}/${typeId}`)
            .then(response => response.json())
            .then(type => {
              document.getElementById('type_id').value = type.type_id;
              document.getElementById('type_name').value = type.type_name;
              document.getElementById('description').value = type.description || '';

              document.getElementById('modalTitle').textContent = '编辑活动分类';

              // 显示模态框
              const modal = new bootstrap.Modal(document.getElementById('typeModal'));
              modal.show();
            })
            .catch(error => {
              console.error('获取分类信息出错:', error);
              showToast('获取分类信息出错', 'error');
            });
  }

  // 保存活动分类
  function saveActivityType() {
    const typeName = document.getElementById('type_name').value.trim();

    if (!typeName) {
      showToast('请输入分类名称', 'error');
      return;
    }

    const activityType = {
      type_name: typeName,
      description: document.getElementById('description').value.trim() || null
    };

    const typeId = document.getElementById('type_id').value;
    const isUpdate = typeId !== '';

    const method = isUpdate ? 'PUT' : 'POST';
    const url = isUpdate ? `${API_BASE}/${typeId}` : API_BASE;

    if (isUpdate) {
      activityType.type_id = parseInt(typeId);
    }

    fetch(url, {
      method: method,
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(activityType)
    })
            .then(response => response.json())
            .then(result => {
              if (result === true || (typeof result === 'object' && result !== null)) {
                showToast(isUpdate ? '更新成功' : '添加成功', 'success');
                bootstrap.Modal.getInstance(document.getElementById('typeModal')).hide();
                loadActivityTypes();
              } else {
                showToast(isUpdate ? '更新失败' : '添加失败', 'error');
              }
            })
            .catch(error => {
              console.error('保存出错:', error);
              showToast('保存出错', 'error');
            });
  }

  // 删除活动分类
  function deleteActivityType(typeId) {
    if (!confirm('确定要删除这个活动分类吗？此操作不可恢复！')) {
      return;
    }

    fetch(`${API_BASE}/${typeId}`, {
      method: 'DELETE'
    })
            .then(response => response.json())
            .then(result => {
              if (result === true) {
                showToast('删除成功', 'success');
                loadActivityTypes();
              } else {
                showToast('删除失败', 'error');
              }
            })
            .catch(error => {
              console.error('删除出错:', error);
              showToast('删除出错', 'error');
            });
  }

  // 显示Toast提示
  function showToast(message, type) {
    const toastEl = document.getElementById('toast');
    const toastMessageEl = document.getElementById('toastMessage');

    toastMessageEl.textContent = message;
    toastEl.classList.remove('text-bg-success', 'text-bg-danger');

    if (type === 'success') {
      toastEl.classList.add('text-bg-success');
    } else {
      toastEl.classList.add('text-bg-danger');
    }

    const toast = new bootstrap.Toast(toastEl);
    toast.show();
  }

  // 清空表单
  document.getElementById('typeModal').addEventListener('hidden.bs.modal', function () {
    document.getElementById('typeForm').reset();
    document.getElementById('type_id').value = '';
    document.getElementById('modalTitle').textContent = '新增活动分类';
  });
</script>
</body>
</html>
